﻿using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using SqlSugar.Extensions;
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;

namespace CoreShop.App.Units
{
    public class ExportUtil
    {
        public static bool NPOIExportForDataGridview(Dictionary<string, DataGridView> gridViews, string FileName)
        {
            MemoryStream ms = new MemoryStream();
            //创建工作薄      
            HSSFWorkbook book = new HSSFWorkbook();
            ISheet sheet;
            foreach (KeyValuePair<string, DataGridView> item in gridViews)
            {
                //用工作簿对象创建工作表
                sheet = book.CreateSheet(item.Key);
                IRow row0 = sheet.CreateRow(0);
                foreach (DataGridViewColumn col in item.Value.Columns)
                {
                    row0.CreateCell(col.Index).SetCellValue(col.HeaderText);
                    sheet.SetColumnWidth(col.Index, 45 * col.Width);
                }

                int rowIndex = 1;
                foreach (DataGridViewRow row in item.Value.Rows)
                {
                    HSSFRow dataRow = sheet.CreateRow(rowIndex) as HSSFRow;
                    foreach (DataGridViewColumn col in item.Value.Columns)
                    {
                        if ((col.ValueType == typeof(DateTime)) && (row.Cells[col.Index].ObjToString() != ""))
                        {
                            dataRow.CreateCell(col.Index).SetCellValue((row.Cells[col.Index].Value).ObjToString());
                        }
                        else
                        {
                            dataRow.CreateCell(col.Index).SetCellValue(row.Cells[col.Index].Value.ObjToString());
                        }
                    }
                    rowIndex++;
                }
            }
            book.Write(ms);
            ms.Flush();
            ms.Position = 0;
            sheet = null;
            book = null;
            FileStream fs = new FileStream(FileName, FileMode.Create, FileAccess.Write);
            byte[] data = ms.ToArray();
            fs.Write(data, 0, data.Length);
            fs.Flush();
            fs.Close();
            data = null;
            ms = null;
            fs = null;
            return true;
        }
    }
}